package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    //登录拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception  {
        //1: 判断访问请求对应的方法头顶是否贴了: @RequireLogin

        if(handler instanceof HandlerMethod){
            //动态请求对象
            //currentUser  hm  --> LoginController.currentUser
            //get    hm  --> LoginController.get
            HandlerMethod hm  = (HandlerMethod) handler;
            //2:如果贴了这个标签, 获取token, 查询用户信息, 根据用户对象是否存在, 判断是否登录
            if(hm.hasMethodAnnotation(RequireLogin.class)){
                String token = request.getHeader("token");
                UserInfo user = userInfoRedisService.getUserByToken(token);
                if(user == null){
                    response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                    return false;
                }
            }
        }
        //3:如果没贴, 直接放行
        return true;
    }
    
}
